<template>
  <div class="user-edit">
    <!-- Drawer抽屉 -->
    <Drawer :title="title" v-model="visible" width="720" draggable :mask-closable="type=='0'">
      <div :style="{maxHeight: maxHeight}" class="drawer-content">
        <div class="user-title">
          <div class="info-title">基本信息</div>
        </div>
        <Form ref="form" :model="form" :rules="formValidate" label-position="top">

          <Row :gutter="32">
            <Col span="12">
              <Form-item label="区域" prop="areaId">
                <!-- <area-choose 
                  @on-change="handleSelectAreaChoose" 
                  :selectDep="form.areaName"
                  style="width: 200px" 
                ></area-choose> -->
                <Poptip trigger="click" placement="right-start" title="区域" width="100%">
                  <Input v-model="form.areaName" style="width:100%" readonly />
                  <div slot="content" style="position:relative;min-height:5vh">
                    <Tree :data="areaData" :load-data="loadData" @on-select-change="selectTreeEdit" ref="treeTwo"></Tree>
                    <Spin size="large" fix v-if="loadingEdit"></Spin>
                  </div>
                  </Poptip> 
              </Form-item>
            </Col>
          </Row>
          <Row :gutter="32">
            <Col span="12">
              <FormItem label="用户名" prop="accountName">
                <Input v-model="form.accountName" />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="登录代码" prop="unitCode">
                <Input v-model="form.unitCode" />
              </FormItem>
            </Col>
          </Row>
          <Divider />
        </Form>
      </div>
      <div class="drawer-footer br" v-show="type!=='0'">
        <Button type="primary" :loading="submitLoading" @click="submit">提交</Button>
        <Button @click="visible = false">取消</Button>
      </div>
    </Drawer>
  </div>
</template>

<script>
import { 
  getAllRoleList, 
  getOfficeVoList, 
  createDepartmentUser, 
  updateDepartmentUser, 
  getBusinessList,
  getAreaByAreaLevel,
  loadArea
} from "@/api/index";
import {
  validateUsername,
  validateMobile,
  validatePassword
} from "@/libs/validate";
import departmentTreeChoose from "@/views/my-components/xboot/department-tree-choose";
import uploadPicInput from "@/views/my-components/xboot/upload-pic-input";
import SetPassword from "@/views/my-components/xboot/set-password";
import AreaChoose from "../../my-components/xboot/area-choose";
import DepartmentChoose from "../../my-components/xboot/department-choose";
export default {
  name: "user",
  components: {
    DepartmentChoose,
    AreaChoose,
    departmentTreeChoose,
    uploadPicInput,
    SetPassword
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object
    },
    type: {
      type: String,
      default: "0"
    }
  },
  data() {
    return {
      type: 0,
      officeData: [],
      businessData: [],
      dataList: [
        {
         id: 1,
         name: "省级部门"
        },
        {
          id: 2,
          name: "市级部门"
        },
        {
          id: 3,
          name: "区县部门"
        },
        {
          id: 4,
          name: "乡镇部门"
        }
      ],
      visible: this.value,
      title: "",
      passColor: "",
      submitLoading: false,
      maxHeight: 510,
      form: {
        id: '',
        areaId: '',
        accountName: '',
        unitCode: '',
        areaName: []
      },
      formValidate: {
        // 表单验证规则
        username: [
          { required: true, message: "请输入登录账号", trigger: "blur" },
          { validator: validateUsername, trigger: "blur" }
        ],
        nickname: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validateMobile, trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validatePassword, trigger: "blur" }
        ],
      },
      roleList: [],
      loadingEdit: true,
      areaData: []
    };
  },
  methods: {
    init() {
      this.getRoleList();
      this.getBusinessList();
      this.getAreaList()
    },
    getAreaList() {
      this.loadingEdit = true;
      getAreaByAreaLevel().then(res => {
        this.loadingEdit = false;
          if (res.success) {
            res.result.forEach(function(e) {
              if (e.isParent) {
                e.loading = false;
                e.children = [];
              }
            });
            this.areaData = res.result;
          }
        });
    },
    loadData(item, callback) {
      loadArea(item.id).then(res => {
        if (res.success) {
          res.result.forEach(function(e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
              e._loading = false;
            }
          });
          callback(res.result);
        }
      });
    },
    getRoleList() {
      getAllRoleList().then(res => {
        if (res.success) {
          this.roleList = res.result;
        }
      });
    },

    getBusinessList() {
      getBusinessList().then(res => {
        if (res.success) {
          this.businessData = res.result.content;
        }
      });
    },
    selectTreeEdit(v) {
      // console.log(this.$refs.tree.getSelectedNodes())
      console.log(v)
      if (v.length > 0) {
        for (let attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = "";
          }
        }
        let str = JSON.stringify(v[0]);
        let data = JSON.parse(str);
        // this.editTitle = data.title;
        this.form.areaId = data.id;
        this.form.areaName = data.parentTitle + '/' + data.title
      } else {
        this.cancelEdit();
      }
    },
    cancelEdit() {
      let data = this.$refs.tree.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
      this.$refs.form.resetFields();
      delete this.form.id;
    },
    getOfficeData() {
      getOfficeVoList().then(res => {
        console.log(res.result);
        if (res.success) {
          this.officeData = res.result;
        }
      });
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.type === "1") {
            // 编辑
            this.submitLoading = true;
            this.form.type = 0;
            updateDepartmentUser(this.form).then(res => {
              this.submitLoading = false;
              if (res.success) {
                this.$Message.success("操作成功");
                this.$emit("on-submit", true);
                this.visible = false;
              }
            });
          } else {
            // 添加
            this.submitLoading = true;
            this.form.type = 1;
            createDepartmentUser(this.form).then(res => {
              this.submitLoading = false;
              if (res.success) {
                this.$Message.success("操作成功");
                this.$emit("on-submit", true);
                this.visible = false;
              }
            });
          }
        }
      });
    },
    setCurrentValue(value) {
      if (value === this.visible) {
        return;
      }
      if (this.type === "1") {
        this.title = "编辑下级应急管理部门用户";
        this.maxHeight = Number(document.documentElement.clientHeight - 121) + "px";
      } else if (this.type === "2") {
        this.title = "添加下级应急管理部门用户";
        this.maxHeight = Number(document.documentElement.clientHeight - 121) + "px";
      } else {
        this.title = "下级应急管理部门用户用户详情";
        this.maxHeight = "100%";
      }
      // 清空数据
      this.$refs.form.resetFields();
      // let data = this.$refs.treeTwo.getSelectedNodes()[0];
      //           if (data) {
      //             data.selected = false;
      //           }
      if (this.type === "0" || this.type === "1") {
        console.log(this.data)
        // 回显数据
        let data = this.data;
        // 回显
        this.form = data;
      } else {
        this.form = {
          areaId: '',
          accountName: '',
          unitCode: '',
          areaName: ''
        };
      }
      this.visible = value;
    }
  },
  watch: {
    value(val) {
      this.setCurrentValue(val);
    },
    visible(value) {
      this.$emit("input", value);
    }
  },
  mounted() {
    this.init();
    this.getOfficeData();
  }
};
</script>

<style lang="less">
@import "../../../styles/table-common.less";
.drawer-content {
  overflow: auto;
}
.drawer-content::-webkit-scrollbar {
  display: none;
}
.user-title {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  .info-title {
    font-size: 16px;
    color: rgba(0, 0, 0, 0.85);
    display: block;
    margin-right: 16px;
  }
}
.info-header {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  display: block;
  margin-bottom: 16px;
}
</style>

